package com.yc.thread.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestTryLock {
	Lock lock = new ReentrantLock();
	
	public void m1() {
		lock.lock();
		try {
			TimeUnit.SECONDS.sleep(20);
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		
	}
	
	public void MySleep(long time) {
		try {
			TimeUnit.SECONDS.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 最多尝试3次
	 */
	public void m2() {
		
		for (int i = 0; i < 3; i++) {//最多尝试3次
			if (lock.tryLock()) {
				try {
					System.out.println("获取锁成功");
					break;
				} finally {
					lock.unlock();
				}
			} else {
				System.out.println("尝试失败"+i);
			}
			MySleep(1);
		}
		
	}
	
	/**
	 * 一段一段时间的尝试
	 */
	public void m3() {
		for (int i = 0; i < 3; i++) {//最多尝试3次
			
			boolean lockFlag = false;
			try {
				if (lockFlag = lock.tryLock(3, TimeUnit.SECONDS)) {
					System.out.println("获取锁成功");
					break;
				} else {
					System.out.println("尝试失败"+i);
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				if (lockFlag) {//这句话很重要：在没获取到lock之前直接unlock是会报：java.lang.IllegalMonitorStateException
					lock.unlock();
				}
			}
			
		}
	}

	public static void main(String[] args) {
		TestTryLock tt = new TestTryLock();
		new Thread(tt::m1, "T1").start();
//		new Thread(tt::m2, "T2").start();
//		T1.start();
//		T2.start();
		new Thread(tt::m3, "T3").start();
	}

}
